package com.ruoyi.project.mobile.jiaqin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.utils.R;
import com.ruoyi.project.jiaqin.commentreply.domain.NewsCommentReply;
import com.ruoyi.project.jiaqin.commentreply.service.INewsCommentReplyService;
import com.ruoyi.project.jiaqin.company.domain.Company;
import com.ruoyi.project.jiaqin.company.service.ICompanyService;
import com.ruoyi.project.jiaqin.followcompany.domain.JiaqinFollowCompany;
import com.ruoyi.project.jiaqin.followcompany.service.IJiaqinFollowCompanyService;
import com.ruoyi.project.jiaqin.followmember.domain.JiaqinFollowMember;
import com.ruoyi.project.jiaqin.followmember.service.IJiaqinFollowMemberService;
import com.ruoyi.project.jiaqin.membernewslikes.domain.MemberNewsLikes;
import com.ruoyi.project.jiaqin.membernewslikes.service.IMemberNewsLikesService;
import com.ruoyi.project.jiaqin.news.domain.News;
import com.ruoyi.project.jiaqin.news.service.INewsService;
import com.ruoyi.project.jiaqin.newsclass.domain.NewsClass;
import com.ruoyi.project.jiaqin.newsclass.service.INewsClassService;
import com.ruoyi.project.jiaqin.newscomment.domain.NewsComment;
import com.ruoyi.project.jiaqin.newscomment.service.INewsCommentService;
import com.ruoyi.project.jiaqin.newsimg.domain.NewsImg;
import com.ruoyi.project.jiaqin.newsimg.service.INewsImgService;
import com.ruoyi.project.system.member.domain.Member;
import com.ruoyi.project.system.member.service.IMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/api/jq/news")
public class ApiNewsController {

    @Autowired
    private INewsService iNewsService;
    @Autowired
    private INewsClassService iNewsClassService;
    @Autowired
    private INewsCommentService iNewsCommentService;
    @Autowired
    private INewsCommentReplyService iNewsCommentReplyService;
    @Autowired
    private IMemberNewsLikesService iMemberNewsLikesService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 获取热门新闻
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/getNews")
    public R getNews(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum
            ,@RequestParam(value="pageSize",defaultValue="5",required = false) Integer pageSize){
        HashMap<String, Object> map = new HashMap<>();
        PageInfo pageInfo = iNewsService.getNewss(pageNum,pageSize);
        map.put("data",pageInfo);
        return R.ok(map);
    }

    /**
     * 获取热门新闻(视频)
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/getNewsByTypeVideo")
    public R getNewsByTypeVideo(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum
            ,@RequestParam(value="pageSize",defaultValue="5",required = false) Integer pageSize,
                                String newsClassId){
        HashMap<String, Object> map = new HashMap<>();
        PageInfo pageInfo = iNewsService.getNewssByTypeVideo(pageNum,pageSize,newsClassId);
        map.put("data",pageInfo);
        return R.ok(map);
    }

    /**
     * 获取热门新闻(文章)
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/getNewsByTypeArticle")
    public R getNewsByTypeArticle(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum
            ,@RequestParam(value="pageSize",defaultValue="5",required = false) Integer pageSize){
        HashMap<String, Object> map = new HashMap<>();
        PageInfo pageInfo = iNewsService.getNewssByTypeArticle(pageNum,pageSize);
        map.put("data",pageInfo);
        return R.ok(map);
    }

    /**
     * 获取新闻分类列表
     * @return
     */
    @GetMapping("/getNewsClass")
    public R getNewsClass(){
        HashMap<String, Object> map = new HashMap<>();
        List<NewsClass> list = iNewsClassService.selectNewsClassList(new NewsClass());
        map.put("data",list);
        return R.ok(map);
    }

    @Autowired
    private INewsImgService newsImgService;
    /**
     * 根据新闻分类ID查询新闻列表
     *
     *  @param type：0-关注 1-推荐 2-本地
     *  @param memberId：用户ID
     * @return
     */
    @GetMapping("/getNewsByNewsClassId")
    public R getNewsClass(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum
            ,@RequestParam(value="pageSize",defaultValue="5",required = false) Integer pageSize,String newsClassId,
                          Integer type, String memberId){
        HashMap<String, Object> map = new HashMap<>();
        News news = new News();
        news.setNewsClassId(newsClassId);
        if (type != null) {
            // 1-推荐
            if (type == 1) {
                PageHelper.startPage(pageNum,pageSize);
                List<News> list = iNewsService.selectNewsListByNumSee(news);
                if (list.size() > 0) {
                    for (News N : list) {
                        NewsImg newsImg = new NewsImg();
                        newsImg.setNewsId(N.getId());
                        List<NewsImg> newsImgList = newsImgService.selectNewsImgList(newsImg);
                        if (newsImgList.size() > 0) {
                            N.setNewsImg(newsImgList);
                        }
                    }
                }
                PageInfo<News> pageInfo = new PageInfo<>(list);
                map.put("data",pageInfo);
                return R.ok(map);
            } else if (type == 2) {// 2-本地
                Member member = memberService.selectMemberById(memberId);
                news.setProvince(member.getProvince());
                PageHelper.startPage(pageNum,pageSize);
                List<News> list = iNewsService.selectNewsList(news);
                if (list.size() > 0) {
                    for (News N : list) {
                        NewsImg newsImg = new NewsImg();
                        newsImg.setNewsId(N.getId());
                        List<NewsImg> newsImgList = newsImgService.selectNewsImgList(newsImg);
                        if (newsImgList.size() > 0) {
                            N.setNewsImg(newsImgList);
                        }
                    }
                }
                PageInfo<News> pageInfo = new PageInfo<>(list);
                map.put("data",pageInfo);
                return R.ok(map);
            }
        } else {
            PageHelper.startPage(pageNum,pageSize);
            List<News> list = iNewsService.selectNewsList(news);
            if (list.size() > 0) {
                for (News N : list) {
                    NewsImg newsImg = new NewsImg();
                    newsImg.setNewsId(N.getId());
                    List<NewsImg> newsImgList = newsImgService.selectNewsImgList(newsImg);
                    if (newsImgList.size() > 0) {
                        N.setNewsImg(newsImgList);
                    }
                }
            }
            PageInfo<News> pageInfo = new PageInfo<>(list);
            map.put("data",pageInfo);
            return R.ok(map);
        }
        return R.ok(map);
    }

    @Autowired
    private ICompanyService companyService;
    @Autowired
    private IMemberService memberService;
    @Autowired
    private IJiaqinFollowCompanyService jiaqinFollowCompanyService;
    @Autowired
    private IJiaqinFollowMemberService jiaqinFollowMemberService;
    /**
     * 根据新闻Id获取新闻详情
     * @param id
     * @return
     *
     */
    @GetMapping("/getNewsById")
    public R getNewsById(String id,String userId){
        if (userId == null || userId.equals("")) {
            return R.error("缺少用户ID");
        }
        HashMap<String,Object> map = new HashMap<>();
        News news = iNewsService.selectNewsById(id);

        NewsImg newsImg = new NewsImg();
        newsImg.setNewsId(id);
        List<NewsImg> newsImgList = newsImgService.selectNewsImgList(newsImg);
        if (newsImgList.size() > 0) {
            news.setNewsImg(newsImgList);
        }

        if(iMemberNewsLikesService.selectMemberNewsLikesById(userId,id) == null){
            news.setIsLikes(false);
        }else{
            news.setIsLikes(true);
        }
        // 是否是企业
        if (news.getMemberId() != null) {
            Member memberById = memberService.selectMemberById(news.getMemberId());
            if (memberById != null) {
                Company company = companyService.selectCompanyByMemberId(news.getMemberId());
                if (company != null) {
                    JiaqinFollowCompany followCompany = jiaqinFollowCompanyService.selectJiaqinFollowMemberByMemberIdAndToCompanyId(userId, company.getId());
                    news.setIsCompany(1);// 企业
                    news.setMemberId(memberById.getId());// 企业ID
                    news.setHeadpic(memberById.getHeadpic());// 企业头像
                    news.setMemberName(memberById.getUsername());// 企业姓名
                    if (followCompany != null) {
                        news.setIsCollect(1);
                    } else {
                        news.setIsCollect(0);
                    }
                } else {
                    JiaqinFollowMember followMember = jiaqinFollowMemberService.selectJiaqinFollowMemberByMemberIdAndToMemberId(userId, news.getMemberId());
                    news.setIsCompany(0);// 个人
                    news.setMemberId(news.getMemberId());// 个人ID
                    news.setHeadpic(memberById.getHeadpic());// 个人头像
                    news.setAuthor(memberById.getUsername());// 个人姓名
                    if (followMember != null) {
                        news.setIsCollect(1);
                    } else {
                        news.setIsCollect(0);
                    }
                }
            }
        }
        //浏览量+1
//        Long numSeeCache = redisTemplate.opsForValue().increment(id,1);
//        news.setNumSee(news.getNumSee()+numSeeCache);
        News news1 = new News();
        news1.setId(id);
        news1.setNumSee(news.getNumSee() + 1);
        iNewsService.updateNews(news1);
        map.put("data",news);
        return R.ok(map);
    }

    /**
     * 用户点赞新闻
     * @param userId
     * @param newsId
     * @return
     */
    @GetMapping("/likesNews")
    public R likesNews(String userId,String newsId){
        MemberNewsLikes memberNewsLikes = iMemberNewsLikesService.selectMemberNewsLikesById(userId,newsId);
        if(memberNewsLikes != null){
            return R.error("点赞失败:已经点过赞了");
        }
        return iNewsService.likesNews(userId,newsId)>0?R.ok("点赞成功"):R.error("点赞失败");
    }

    /**
     * 用户取消点赞新闻
     * @param userId
     * @param newsId
     * @return
     */
    @GetMapping("/unLikesNews")
    public R unLikesNews(String userId,String newsId){
        MemberNewsLikes memberNewsLikes = iMemberNewsLikesService.selectMemberNewsLikesById(userId,newsId);
        if(memberNewsLikes == null){
            return R.error("取消失败:还未点赞");
        }
        return iNewsService.unlikesNews(userId,newsId)>0?R.ok("取消成功"):R.error("取消失败");
    }

    /**
     * 评论新闻
     * @param userId
     * @param newsId
     * @param content
     * @return
     */
    @PostMapping("/commentNews")
    public R commentNews(@RequestBody NewsComment newsComment){
        if(newsComment.getUserId() == null || newsComment.getUserId().equals("")){
            return R.error("用户ID不能为空");
        }
        if(newsComment.getNewsId() == null || newsComment.getNewsId().equals("")){
            return R.error("新闻ID不能为空");
        }
        if(newsComment.getContent() == null || newsComment.getContent().equals("")){
            return R.error("评论内容不能为空");
        }
        newsComment.setUserId(newsComment.getUserId());
        newsComment.setNewsId(newsComment.getNewsId());
        newsComment.setContent(newsComment.getContent());
        newsComment.setCommentAt(new Date());
        //newsComment.setStatus(0);
        //插入评论并更新评论数量
        iNewsCommentService.commentNews(newsComment);
//        System.out.println(newsComment);
        return R.ok();

    }

    /**
     * 回复
     * @param fromUserId 回复用户
     * @param toUserId  被回复用户
     * @param content   回复内容
     * @param commentId 评论ID
     * @return
     */
    @GetMapping("/replyComment")
    public R replyComment(String fromUserId,String toUserId,String content,String commentId){
        if(fromUserId == null || fromUserId.equals("")){
            return R.error("用户ID不能为空");
        }
        if(toUserId == null || toUserId.equals("")){
            return R.error("用户ID不能为空");
        }
        if(commentId == null || commentId.equals("")){
            return R.error("评论ID不能为空");
        }
        if(content == null || content.equals("")){
            return R.error("回复内容不能为空");
        }
        if(fromUserId.equals(toUserId)){
            return R.error("不可回复自己");
        }
        NewsCommentReply newsCommentReply = new NewsCommentReply();
        newsCommentReply.setFromUserId(fromUserId);
        newsCommentReply.setToUserId(toUserId);
        newsCommentReply.setContent(content);
        newsCommentReply.setNewsCommentId(commentId);
        newsCommentReply.setReplyAt(new Date());
        newsCommentReply.setStatus(0);
        iNewsCommentReplyService.insertNewsCommentReply(newsCommentReply);
        return R.ok();
    }

    /**
     * 根据评论ID获取回复
     * @param commentId
     * @return
     */
    @GetMapping("/getReply")
    public R getReply(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum
            ,@RequestParam(value="pageSize",defaultValue="5",required = false) Integer pageSize,String commentId){
        HashMap<String,Object> map = new HashMap<>();
        PageInfo pageInfo = iNewsCommentReplyService.selectNewsCommentReplyListByCommentId(pageNum,pageSize,commentId);
        map.put("data",pageInfo);
        return R.ok(map);
    }

    /**
     * 根据新闻ID获取新闻评论
     * @return
     */
    @GetMapping("/getNewsComment")
    public R getNewsComment(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum
            ,@RequestParam(value="pageSize",defaultValue="5",required = false) Integer pageSize,String newsId, String memberId){
        HashMap<String,Object> map = new HashMap<>();
        PageInfo<NewsComment> pageInfo = iNewsCommentService.getNewsCommentByNewsId(pageNum,pageSize,newsId,memberId);
        map.put("data",pageInfo);
        return R.ok(map);
    }

    /**
     * 根据评论ID获取评论详情
     * @return
     */
    @GetMapping("/getNewsCommentById")
    public R getNewsComment(String commentId){
        HashMap<String,Object> map = new HashMap<>();
        NewsComment newsComment= iNewsCommentService.selectNewsCommentByIdA(commentId);
        map.put("data",newsComment);
        return R.ok(map);
    }


}
